package com.duobaoyu.dby.supply.db.repository.order.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duobaoyu.dby.supply.db.entity.config.OperationLog;
import com.duobaoyu.dby.supply.db.repository.order.OperationLogRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author chenms
 * @date 2023/10/21 12:06 PM
 */
@Repository
@RequiredArgsConstructor
public class OperationLogRepositoryImpl implements OperationLogRepository {

    private final MongoTemplate mongoTemplate;

    @Override
    public boolean save(OperationLog operationLog) {
        OperationLog save = mongoTemplate.save(operationLog);
        return Optional.ofNullable(save).map(OperationLog::getId).map(StringUtils::isNotBlank).orElse(false);
    }

    @Override
    public boolean saveBatch(List<OperationLog> operationLogList) {
        Collection<OperationLog> operationLogs = mongoTemplate.insertAll(operationLogList);
        return Optional.ofNullable(operationLogs).map(item -> item.stream().anyMatch(operationLog -> StringUtils.isBlank(operationLog.getId()))).orElse(false);
    }

    @Override
    public List<OperationLog> list(Query query) {
        return mongoTemplate.find(query, OperationLog.class);
    }

    @Override
    public Page<OperationLog> page(Page page, Query query) {
        // 12. 总记录数
        long total = mongoTemplate.count(query, OperationLog.class);
        // 8. 查询返回指定字段 (自定义列表)
        //query.fields().include()
        // 10. 分页、排序
        int pageNo = Long.valueOf(page.getCurrent() - 1).intValue();
        int size = Long.valueOf(page.getSize()).intValue();
        query.with(PageRequest.of(pageNo, size, Sort.by(Sort.Order.asc("create_time"))));
        List<OperationLog> operationLogs = mongoTemplate.find(query, OperationLog.class);
        page.setTotal(total);
        page.setRecords(operationLogs);
        return page;
    }

}
